﻿using System;
using System.Collections.Generic;
using System.Text;
using AspNetCs.IDAL;
using AspNetCs.DALFactory;
using AspNetCs.Model;
using System.Data;
using System.Web;
using AspNetCs.Enumerations.Channel_Enum;
using AspNetCs.Common;
using System.IO;
using System.Reflection;
using AspNetCs.Config;
using System.Text.RegularExpressions;

namespace AspNetCs.Bll
{
    public class Temple
    {
        private ITemple TempleDAl = Conn.CreateTemple();
        /// <summary>
        /// 添加
        /// </summary>
        /// <param name="model"></param>
        /// <param name="Msg"></param>
        /// <returns></returns>
        public int Add(Temple_Model model, out string Msg)
        {
            Msg = "参数不能为空！";
            if (model == null) return -2;
            int result = TempleDAl.Add(model);
            if (result > 0)
            {
                Msg = "添加成功";
            }
            else
            {
                Msg = "添加失败!";
            }
            return result;
        }
        public int delete(string filter)
        {
            if (filter == "") return -1;
            return TempleDAl.delete(filter);
        }

        public DataTable GetDataTable(string filter)
        {
            return TempleDAl.GetDataTable(filter);
        }

        public Temple_Model GetModel(DataRow dr)
        {
            return TempleDAl.GetModel(dr);
        }
        public Temple_Model GetModel(int id)
        {
            Temple_Model model = new Temple_Model();
            DataTable dt = GetDataTable(" id=" + id);
            foreach (DataRow dr in dt.Rows)
            {
                model = this.GetModel(dr);
            }
            return model;
        }

        public int Update(Temple_Model model, out string Msg)
        {
            int result = 0;
            Msg = "参数不能为空";
            if (model == null) return -1;
            result = TempleDAl.Update(model);
            if (result <= 0)
            {
                Msg = "更新失败";
            }
            else
            {
                Msg = "更新成功";
            }
            return result;
        }

        /// <summary>
        /// 根据频道ID，与类型返回模板数据的列表
        /// </summary>
        /// <param name="channel_enum"></param>
        /// <param name="Types"></param>
        /// <returns></returns>
        public DataTable GetDataTable(Channel_Type channel_enum, int Types)
        {
            string filter = " ChannelID=" + ((int)channel_enum).ToString();

            if (Types > 0)
            {
                filter += " and Types=" + Types.ToString();
            }
            filter += " order by point asc";
            return GetDataTable(filter);
        }

        /// <summary>
        /// 当前模板所需点数
        /// </summary>
        /// <param name="_id"></param>
        /// <returns></returns>
        public string TemplePointStr(object pointnum)
        {
            string Result = "";
            if (StringHelper.isNumber_decimal(pointnum.ToString()) > 0)
            {
                Result = "<span style='color:#666666'>(所需点数:" + pointnum.ToString() + "点)</span>";
            }
            else
            {
                Result = "<span style='color:#666666'>免费</span>";
            }

            return Result;

        }

        /// <summary>
        /// 如果文件不存在，就生成模板
        /// </summary>
        /// <param name="TemplePath">模板生成的路径,[绝对路径]</param>
        /// <param name="pagename">页面名称[必须为:馆号.html]</param>
        /// <param name="channel_str">频道</param>
        /// <param name="IsCreate">是否是直接生成</param>
        /// <returns></returns>
        public bool TempleCreate(string TemplePath, string pagename, Channel_Type channel_str, bool IsCreate)
        {
            bool result = false;
            if (IsCreate != true)
            {
                IsCreate = File.Exists(TemplePath) ? false : true;
            }
            try
            {

                if (IsCreate)
                {
                    string[] pageArry = StringHelper.SplitString(pagename, ".");
                    if (pageArry.Length >= 2)
                    {
                        StringBuilder sb = new StringBuilder();
                        if (StringHelper.ReadConfig(channel_str.ToString()) != "")
                        {
                            SiteConfigInfo configInfo = new SiteConfigInfo();
                            configInfo = System_Lable.SystemGetCache;



                            Type t = Type.GetType(StringHelper.ReadConfig(channel_str.ToString()));
                            System.Reflection.MethodInfo[] methods = t.GetMethods();//获得数据类型(这里是Class类)的所有公共方法成员
                            MethodInfo method = t.GetMethod("CurrTempleContent");//获得数据类型的指定名称的公共方法成员，注意是GetMethod而不是GetMethods 
                            method.Invoke(Activator.CreateInstance(t), new Object[] { pageArry[0], channel_str, configInfo, TemplePath });



                            // Assembly.Load(path).CreateInstance(ClassName)


                            // PropertyInfo properties = t.GetProperty("CreateNew");//获得数据类型的公共属性成员
                            //Type t1 = properties.DeclaringType;
                            //string s = t1.FullName;
                            result = true;
                        }

                    }
                }
            }
            catch
            {
                result = false;
            }
            return result;
        }

        public bool TempleCreate(string TemplePath, string pagename, Channel_Type channel_str)
        {
            return TempleCreate(TemplePath, pagename, channel_str, false);
        }



        /// <summary>
        /// 读取模板文件内容
        /// </summary>
        /// <param name="PathUrl">文件路径[绝对路径]</param>
        /// <param name="TableName">表名</param>
        /// <param name="HeadAddContent">需要在head之间添加的内容</param>
        /// <returns></returns>
        public StringBuilder WriteHtml(string PathUrl, string HeadAddContent)
        {
            StringBuilder stb = new StringBuilder();
            try
            {

                System.IO.StreamReader str = new System.IO.StreamReader(PathUrl);
                string html = null;
                while ((html = str.ReadLine()) != null)
                {
                    stb.AppendLine((html));

                }
                str.Close();
                Regex headeAdd = new Regex(@"(\<head\>(?<lable>.*?)\<\/head\>)", RegexOptions.Singleline | RegexOptions.IgnoreCase | RegexOptions.Compiled);//获取head头部

                MatchCollection matches = headeAdd.Matches(stb.ToString());
                foreach (Match match in matches)
                {
                    stb.Replace(match.Value.ToString(), "<head>\r\n" + HeadAddContent + match.Groups["lable"].ToString() + "\r\n</head>");
                }
                StringBuilder stbResult = new StringBuilder();
                stbResult.Append(stb);
                return stbResult;

            }
            catch
            {
                return stb;
            }

        }


        public StringBuilder WriteHtml(string PathUrl)
        {
            return WriteHtml(PathUrl, "");

        }




        /// <summary>
        /// 生成模板文件
        /// </summary>
        /// <param name="stb">生成的内容</param>
        /// <param name="CreatePath">模板生成的路径,[绝对路径]</param>
        /// <returns></returns>
        public bool CreateHtmlFile(string stb, string CreatePath)
        {
            bool result = false;
            try
            {
                FileInfo f = new FileInfo(CreatePath);
                if (f.Exists)
                {
                    if (f.IsReadOnly)
                    {
                        f.IsReadOnly = false;
                    }
                }
                FileStream Fs = new FileStream(CreatePath, FileMode.Create, FileAccess.ReadWrite);
                StreamWriter sw = new StreamWriter(Fs, Encoding.UTF8);
                sw.Write(stb.ToString());
                sw.Flush();
                Fs.Flush();
                sw.Close();
                Fs.Close();
                result = true;
            }
            catch
            {
                result = false;
            }
            return result;
        }



        /// <summary>
        /// 生成模板文件
        /// </summary>
        /// <param name="stb">生成的内容</param>
        /// <param name="CreatePath">模板生成的路径,[绝对路径]</param>
        /// <returns></returns>
        public bool CreateHtmlFile(StringBuilder stbAnd, string CreatePath)
        {
            return CreateHtmlFile(stbAnd.ToString(), CreatePath);
        }

        public DataTable GetTableColumn(string TbName)
        {
            return TempleDAl.GetTableColumn(TbName);

        }

        public DataTable GetTable(string TbName, string filter)
        {
            return TempleDAl.GetTableColumn(TbName, filter);
        }




        /// <summary>
        /// 创建纪念馆、公墓、宗祠...等等显示的选择的模块
        /// </summary>
        /// <param name="ChannelType">频道类型</param>
        /// <param name="Types">类型</param>
        /// <param name="CurrentPoint">用户当前点数</param>
        /// <param name="CreateNeedPoint">创建纪念馆、公墓、宗祠..等需要的点数</param>
        /// <returns></returns>
        public string TemplateList(Channel_Type ChannelType, int Types, int CurrentPoint, int CreateNeedPoint, out int Recordcount)
        {
            StringBuilder sb = new StringBuilder();
            DataTable dataTable = GetDataTable(ChannelType, Types);
            Recordcount = dataTable.Rows.Count;
            if (dataTable.Rows.Count > 0)
            {
                sb.AppendLine("<script type=\"text/javascript\">");
                sb.AppendLine("function checkChange(val)");
                sb.AppendLine("{");
                sb.AppendLine("var hldTemplePoint=document.getElementById(\"hldTemplePoint\");");
                sb.AppendLine("hldTemplePoint.value=val;");
                sb.AppendLine("}");
                sb.AppendLine("</script>");
                string hldTemStr = "<input type=\"hidden\" name=\"hldTemplePoint\" id=\"hldTemplePoint\" value=\"{0}\" />";

                sb.Append("<ul>");

                for (int i = 0; i < dataTable.Rows.Count; i++)
                {
                    sb.Append("<li>");

                    int needPoint = CreateNeedPoint;
                    DataRow row = dataTable.Rows[i];
                    string Thumbimg = row["Thumbimg"].ToString();
                    needPoint += StringHelper.isNumber_int(row["Point"]);

                    string showPoint = StringHelper.isNumber_int(row["Point"]) > 0 ? "点数:" + StringHelper.isNumber_int(row["Point"]).ToString() : "免费";
                    int TemplateId = StringHelper.isNumber_int(row["Id"]);
                    string TemplateName = row["TempleName"].ToString();
                    sb.AppendLine("<table border=\"0\">");
                    sb.AppendLine("<tr>");
                    sb.AppendLine("<td>");
                    sb.AppendLine("<img style=\"width:100px;height:80px;\" src=\"../" + Thumbimg + "\" />");
                    sb.AppendLine("</td>");
                    sb.AppendLine("</tr>");
                    sb.AppendLine("<tr>");
                    sb.AppendLine("<td>");

                    if (CurrentPoint < needPoint)
                    {
                        sb.AppendLine("<input type=\"radio\" name=\"templateId\" onclick=\"checkChange(" + StringHelper.isNumber_decimal(row["Point"].ToString()) + ");\"  disable value=\"" + TemplateId + "\">" + TemplateName + "&nbsp;&nbsp;&nbsp;<span style=\"color:red;\">" + showPoint + "</span>");
                    }
                    else
                    {
                        if (i == 0)
                        {
                            sb.AppendLine("<input type=\"radio\" name=\"templateId\" onclick=\"checkChange(" + StringHelper.isNumber_decimal(row["Point"].ToString()) + ");\"  checked=\"true\" value=\"" + TemplateId + "\">" + TemplateName + "&nbsp;&nbsp;&nbsp;<span style=\"color:red;\">" + showPoint + "</span>");
                            hldTemStr = string.Format(hldTemStr, StringHelper.isNumber_decimal(row["Point"].ToString()));
                        }
                        else
                        {
                            sb.AppendLine("<input type=\"radio\" name=\"templateId\" onclick=\"checkChange(" + StringHelper.isNumber_decimal(row["Point"].ToString()) + ");\"  value=\"" + TemplateId + "\">" + TemplateName + "&nbsp;&nbsp;&nbsp;<span style=\"color:red;\">" + showPoint + "</span>");
                        }
                    }
                    sb.AppendLine("</td>");
                    sb.AppendLine("</tr>");
                    sb.AppendLine("</table>");
                    sb.AppendLine("</li>");
                }
                sb.AppendLine("</ul>");

                sb.AppendLine(hldTemStr);
            }
            else
            {
                sb.AppendLine("暂无任何模板，您无法创建");
            }

            return sb.ToString();
        }


        /// <summary>
        /// 创建纪念馆、公墓、宗祠...等等显示的选择的模块
        /// </summary>
        /// <param name="ChannelType">频道类型</param>
        /// <param name="Types">类型</param>
        /// <param name="CurrentPoint">用户当前点数</param>
        /// <param name="CreateNeedPoint">创建纪念馆、公墓、宗祠..等需要的点数</param>
        /// <returns></returns>
        public string TemplateList(Channel_Type ChannelType, int Types, int CurrentPoint, int CreateNeedPoint)
        {
            int record = 0;
            return TemplateList(ChannelType, Types, CurrentPoint, CreateNeedPoint, out  record);
        }






        /// <summary>
        /// 修改纪念馆、公墓、宗祠...等等显示的选择的模块
        /// </summary>
        /// <param name="ChannelType">频道类型</param>
        /// <param name="Types">类型</param>
        /// <param name="CurrentPoint">用户当前点数</param>
        /// <param name="CreateNeedPoint">修改纪念馆、公墓、宗祠..等需要的点数</param>
        /// <param name="TemplateId">模板编号</param>
        /// <returns></returns>
        public string EditTemplateList(Channel_Type ChannelType, int Types, int CurrentPoint, int Template_Id)
        {

            StringBuilder sb = new StringBuilder();
            //sb.Append("<script type=\"text/javascript\" src=\""++"\"></script>");
            DataTable dataTable = GetDataTable(ChannelType, Types);
            if (dataTable.Rows.Count > 0)
            {
                sb.AppendLine("<script type=\"text/javascript\">");
                sb.AppendLine("function checkChange(vals)");
                sb.AppendLine("{");
                sb.AppendLine("var hldTemplePoint=document.getElementById(\"hldTemplePoint\");");
                sb.AppendLine("hldTemplePoint.value=vals;");
                sb.AppendLine("}");
                sb.AppendLine("</script>");
                sb.AppendLine("<input type=\"hidden\" name=\"hldTemplePoint\" id=\"hldTemplePoint\" value=\"0\" />");



                sb.Append("<ul>");
                for (int i = 0; i < dataTable.Rows.Count; i++)
                {
                    sb.Append("<li>");
                    int needPoint = 0;
                    DataRow row = dataTable.Rows[i];
                    string Thumbimg = row["Thumbimg"].ToString();
                    needPoint += StringHelper.isNumber_int(row["Point"]);
                    string showPoint = needPoint > 0 ? "点数:" + needPoint.ToString() : "免费";
                    int TemplateId = StringHelper.isNumber_int(row["Id"]);
                    string TemplateName = row["TempleName"].ToString();

                    sb.AppendLine("<table border=\"0\"  >");
                    sb.AppendLine("<tr>");
                    sb.AppendLine("<td>");
                    sb.AppendLine("<img style=\"width:100px;height:80px;\" src=\"../" + Thumbimg + "\" />");
                    sb.AppendLine("</td>");
                    sb.AppendLine("</tr>");
                    sb.AppendLine("<tr>");
                    sb.AppendLine("<td>");

                    if (Template_Id == TemplateId)
                    {
                        sb.AppendLine("<input type=\"radio\" name=\"templateId\" onclick=\"checkChange(" + StringHelper.isNumber_decimal(row["Point"].ToString()) + ");\"   checked=\"true\" value=\"" + TemplateId + "\">" + TemplateName + "&nbsp;&nbsp;&nbsp;<span style=\"color:red;\">" + showPoint + "</span>");
                    }
                    else
                    {
                        if (CurrentPoint < needPoint)
                        {
                            sb.AppendLine("<input type=\"radio\" name=\"templateId\" disable value=\"" + TemplateId + "\">" + TemplateName + "&nbsp;&nbsp;&nbsp;<span style=\"color:red;\">" + showPoint + "</span>");
                        }
                        else
                        {
                            sb.AppendLine("<input type=\"radio\" name=\"templateId\" onclick=\"checkChange(" + StringHelper.isNumber_decimal(row["Point"].ToString()) + ");\"  value=\"" + TemplateId + "\">" + TemplateName + "&nbsp;&nbsp;&nbsp;<span style=\"color:red;\">" + showPoint + "</span>");
                        }

                    }

                    sb.AppendLine("</td>");
                    sb.AppendLine("</tr>");
                    sb.AppendLine("</table>");

                    //sb.Append("<script>$(document).ready(function(){ ");
                    //sb.Append("$(\"templateId\").change(function() {");  
                    //sb.Append("alert(\"Option changed!\");"); 
                    //sb.Append("});");
                    //sb.Append("});</script>");


                    //sb.Append("<script>$(function () { ");
                    //sb.Append("if ($.browser.msie) {");
                    //sb.Append("$('input:radio').click(function () { ");
                    //sb.Append("this.blur();");
                    //sb.Append("this.focus(); ");
                    //sb.Append(" });");
                    //sb.Append("}");
                    //sb.Append("});</script>");
                    sb.Append("</li>");
                }
                sb.AppendLine("</ul>");

            }
            return sb.ToString();
        }

    }


}
